1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
|
class Subject(object): def __init__(self): self._observers = []
def attach(self, observer): if observer not in self._observers: self._observers.append(observer)
def detach(self, observer): try: self._observers.remove(observer) except ValueError: pass
def notify(self, modifier=None): for observer in self._observers: if modifier != observer: observer.update()
class Secretary(Subject): def __init__(self, name=''): super(Secretary, self).__init__()
class Observer(object): def __init__(self, name, sub): self._name = name self._sub = sub
def update(self): raise NotImplementedError("Must Implement me")
class StockObserver(Observer): def __init__(self, name, sub): super(StockObserver, self).__init__(name, sub)
def update(self): print '%s 收到消息:%s' % (self._name, self._sub.action) if self._sub.action == "梁所长来了!": print '我马上关闭股票,装做很认真工作的样子!'
class NBAObserver(Observer): def __init__(self, name, sub): super(NBAObserver, self).__init__(name, sub)
def update(self): print '%s 收到消息:%s' % (self._name, self._sub.action) if self._sub.action == "梁所长来了!": print '我马上关闭NBA,装做很认真工作的样子!'
if __name__ == '__main__': dwq = Secretary() xs = NBAObserver("xiaoshuai", dwq) zy = NBAObserver("zouyue", dwq) lm = StockObserver("limin", dwq)
dwq.attach(xs) dwq.attach(zy) dwq.attach(lm)
dwq.action = "去吃饭了!" dwq.notify()
dwq.action = "梁所长来了!" dwq.notify()
|